package com.qianfeng;


import com.qianfeng.mapper.SysRoleMapper;
import com.qianfeng.mapper.UserInfoMapper;
import com.qianfeng.model.SysRole;
import com.qianfeng.model.UserInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyReal extends AuthorizingRealm {
    @Autowired(required = false)
    UserInfoMapper userInfoMapper;
    @Autowired(required = false)
    SysRoleMapper sysRoleMapper;
    //实现授权功能
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("==========进入授权方法=============");
//       1）需要先在shiro框架中，加载当前成功登录的用户角色列表信息
//        实现思路：根据用户的登录账号，来查询当前用户的所有角色列表信息
        UserInfo userInfo= (UserInfo) SecurityUtils.getSubject().getPrincipal();
//       根据用户的user_id查询对应的角色列表信息
        List<SysRole> roles = sysRoleMapper.findRoleListByUserId(userInfo.getUserId());
//      将查询出来的角色列表信息，保存到授权需要返回的返回对象中
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        for(SysRole role:roles) {
            simpleAuthorizationInfo.addRole(role.getRoleFlag());
        }
        return simpleAuthorizationInfo;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("============进入shiro的认证层=============");
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        System.out.println(username);
        //接下来从数据库里面查询信息，假设查到的信息如下
       /* UserInfo userInfo=new UserInfo();
        userInfo.setUserName("wuwen");
        userInfo.setPassword("3344521");*/
        UserInfo userInfo = userInfoMapper.findUserInfoByUsername(username);
        //测试认证，只要登录的帐号是 admin，则允许登录
        /*
            参数1：principal  认证成功后，希望保存到shiro会话中的用户信息
            参数2：credentials 用户身份识别（登录密码）
            参数3：realmName 传递当前 自定义realm的名称  getName()就是获取当前类的类名

         */
//        return new SimpleAuthenticationInfo(userInfo,userInfo.getPassword(),getName());
//        加密以后的方式
        return new SimpleAuthenticationInfo(userInfo,userInfo.getPassword(), ByteSource.Util.bytes(userInfo.getUserName()),getName());
    }
}
